package com.quanyan.user.service.impl;


import com.google.common.base.Function;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimaps;
import com.quanyan.common.constants.Constants;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.NewsDetailMapper;
import com.quanyan.user.mapper.NewsImagesMapper;
import com.quanyan.user.mapper.TbNewsImagesMapper;
import com.quanyan.user.model.db.TbNewsImages;
import com.quanyan.user.model.db.TbNewsImagesExample;
import com.quanyan.user.model.vo.response.ImageObj;
import com.quanyan.user.model.vo.response.RespDynamicDetail;
import com.quanyan.user.model.vo.response.RespImgInfo;
import com.quanyan.user.model.vo.response.RespMyDynamicImages;
import com.quanyan.user.service.NewsImagesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/22.
 */
@Service
public class NewsImagesServiceImpl implements NewsImagesService {

    private static final Logger logger = LoggerFactory.getLogger(NewsImagesServiceImpl.class);

    @Autowired
    private TbNewsImagesMapper tbNewsImagesMapper;

    @Autowired
    private NewsImagesMapper newsImagesMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private NewsDetailMapper newsDetailMapper;


    @Override
    public List<TbNewsImages> findDynamicImages(Integer dynamicId) {
        TbNewsImagesExample tbNewsImagesExample = new TbNewsImagesExample();
        TbNewsImagesExample.Criteria criteriaImg = tbNewsImagesExample.createCriteria();
        criteriaImg.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteriaImg.andNewsIdEqualTo(dynamicId);
        List<TbNewsImages> lstImg =  tbNewsImagesMapper.selectByExample(tbNewsImagesExample);
        return lstImg;
    }


    public List<ImageObj> getDynamicImages(Integer dynamicId) {
        String key = UserConstants.getDynamicImgKey(dynamicId);
        List<ImageObj> lstImg = (List<ImageObj>)myRedisTemplate.get(key);
        if (lstImg == null){
            List<RespDynamicDetail> lstDynamicId = new ArrayList<>();//未在缓存中的动态
            RespDynamicDetail respDynamicDetail = new RespDynamicDetail();
            respDynamicDetail.setId(dynamicId);
            lstDynamicId.add(respDynamicDetail);
            List<ImageObj> lstImages = newsImagesMapper.findNewsImagesObj(lstDynamicId);
            respDynamicDetail.getImages().addAll(lstImages);
            myRedisTemplate.set(UserConstants.getDynamicImgKey(respDynamicDetail.getId()), lstImages, 7);
        }
        return lstImg;
    }


    public void setUpDynamicImg(RespDynamicDetail respDynamicDetail) {
        String key = UserConstants.getDynamicImgKey(respDynamicDetail.getId());
        List<ImageObj> lstImg = (List<ImageObj>)myRedisTemplate.get(key);
        List<RespDynamicDetail> lstDynamicId = new ArrayList<>();//未在缓存中的动态
        if (lstImg != null){
            respDynamicDetail.getImages().addAll(lstImg);
        }else {
            lstDynamicId.add(respDynamicDetail);
        }
        if (lstDynamicId.size() > 0){
            List<ImageObj> lstImages = newsImagesMapper.findNewsImagesObj(lstDynamicId);
            respDynamicDetail.getImages().addAll(lstImages);
            myRedisTemplate.set(UserConstants.getDynamicImgKey(respDynamicDetail.getId()),lstImages,7);
        }
    }

    @Override
    public void findNewsImages(List<RespDynamicDetail> lst) {
        logger.info("开始查询动态图片：{}",lst.toString());
        List<RespDynamicDetail> lstDynamicId = new ArrayList<>();//未在缓存中的动态
        for (RespDynamicDetail respDynamicDetail : lst ){
            String key = UserConstants.getDynamicImgKey(respDynamicDetail.getId());
            List<ImageObj> lstImg = (List<ImageObj>)myRedisTemplate.get(key);
            if (lstImg != null){
                respDynamicDetail.getImages().addAll(lstImg);
            }else {
                lstDynamicId.add(respDynamicDetail);
            }
        }

        if(lstDynamicId.size() > 0){
            List<ImageObj> lstImages = newsImagesMapper.findNewsImagesObj(lstDynamicId);
            /****===========按动态分组=============****/
            ImmutableSet digits = ImmutableSet.of(lstImages.toArray());
            Function<ImageObj, Integer> topicImg = new Function<ImageObj, Integer>() {
                @Override
                public Integer apply(ImageObj tbNewsImages) {
                    return tbNewsImages.getNewsId();
                }
            };
            ImmutableListMultimap<Integer, ImageObj> topicImgList = Multimaps.index(digits, topicImg); //分组后
            for (RespDynamicDetail respDynamicDetail : lst ){
                List<ImageObj> lstTbImg = topicImgList.get(respDynamicDetail.getId());//获取该动态的所有图片
                if (lstTbImg.size() > 0){
                    respDynamicDetail.getImages().addAll(lstTbImg);
                    myRedisTemplate.set(UserConstants.getDynamicImgKey(respDynamicDetail.getId()),lstTbImg,7);
                }
            }
        }
    }

    /**
     *
     * @param uid 用户id
     * @param size 显示的图片
     * @return
     */
    @Override
    public RespMyDynamicImages getMyDynamicImages(Integer uid, Integer size) {
        RespMyDynamicImages myDynamicImages = new RespMyDynamicImages();
        try {
            List<RespImgInfo> imgInfos = newsImagesMapper.getMyDynamicImages(uid,size);
            Integer count = newsDetailMapper.myDynamicCount(uid);
            myDynamicImages.setDynamicCount(count);
            myDynamicImages.setImgInfos(imgInfos);
        } catch (Exception e) {
            logger.error("用户ID为：【{}】获取我的动态图片失败:{}",uid,e);
            myDynamicImages.setDynamicCount(0);
            myDynamicImages.setImgInfos(new ArrayList<RespImgInfo>());
            return myDynamicImages;
        }
        return myDynamicImages;
    }
}
